package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetBehaviorV2;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PictureAdapter;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CommentService;
import com.srwl.mytx.service.ForwardService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.TextUtil;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.CommentBottomBar;
import com.srwl.mytx.widget.ForwardCommentView;
import com.srwl.mytx.widget.ForwardDonationView;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.PeriscopeLayout;
import com.srwl.mytx.widget.TitleBar;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import qiu.niorgai.StatusBarCompat;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 转发捐赠详情页面
 * 和TopicDetailActivity 很多逻辑相似
 */
public class ForwardDetailsActivity extends BaseActivity implements ForwardCommentView.InteractionListener, CommentBottomBar.InteractionListener, ForwardDonationView.InteractionListener, TitleBar.InteractionListener, BottomDialog.InteractionListener {
    private static final String TAG = "ForwardDetailsActivity";
    private int lastState;

    public static void startActivity(Context context, String forwardId) {
        context.startActivity(new Intent(context, ForwardDetailsActivity.class).putExtra("forwardId", forwardId));
    }

    private Forward forward;
    private User manager;//该笔转赠锁依附的主题的管理员用户信息
    private User targetUser;
    private PictureAdapter pictureAdapter;
    private Handler handler = new Handler();
    private BottomSheetBehaviorV2<View> bottomSheetBehavior;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refreshLayout.setFooterView(new NodataFooter(ForwardDetailsActivity.this));
        }
    };
    //    @BindView(R.id.iv_chat)
//    ImageView iv_chat;
    @BindView(R.id.top_bar)
    TitleBar topBar;
    @BindView(R.id.tv_reason)
    TextView tv_forwardReason;
    @BindView(R.id.tv_receipt)
    TextView tv_receipt;

    @BindView(R.id.rv_picture_list)
    RecyclerView rv_pictureList;
    @BindView(R.id.comment_view)
    ForwardCommentView commentView;
    //    @BindView(R.id.tv_reward)
//    TextView tv_goodsPrice;


    @BindView(R.id.sv_container)
    NestedScrollView sv_container;
    @BindView(R.id.periscope_layout)
    PeriscopeLayout periscopeLayout;
    @BindView(R.id.video_player)
    JzvdStd videoPlayer;

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.comment_bottom_bar)
    CommentBottomBar commentBottomBar;
    @BindView(R.id.donation_view)
    ForwardDonationView donationView;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_username)
    TextView tv_userName;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.tv_address)
    TextView tv_address;
    private boolean bottomBarIsHide;
    private boolean isShowingHideAnimate;
    private boolean isShowingDisplayAnimate;
    private int scrollY;
    private boolean hasVideo;
    private ViewAnimator viewAnimator;//bottomBar滑动动画

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            finish();
        }
        setContentView(R.layout.activity_forward_details);
        ButterKnife.bind(this);
        initBottomSheetBehavior();
        topBar.init("转发捐赠详情", this);
        forward = getIntent().getParcelableExtra(Constant.EXTRA_INFO_FORWARD);
        if (forward != null) {
            Log.d(TAG, forward.toString());
            init();
        } else {
            String forwardId = getIntent().getStringExtra("forwardId");
            loadData(forwardId);
        }
        setOnScrollListener();


    }

    private void init() {
        manager = forward.getManagerUser();
        targetUser = forward.getTargetUser();

        if (targetUser != null) {
            //Glide.with(this).load(targetUser.getAvatar()).error(R.drawable.tx_default_avatar_1).into(iv_avatar);
            GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
            tv_userName.setText(targetUser.getUsername());
        }
        commentView.init(forward, this);
        hasVideo = !TextUtils.isEmpty(forward.getVideo());
        if (hasVideo) {
            //改变一些ui,适配VideoPlayer
            videoPlayer.setVisibility(View.VISIBLE);
            //判断是否是刘海屏（对华为 小米 oppo vivo 4个手机品牌做判断）
            NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
                @Override
                public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                    Log.i(TAG, "Is this screen notch? " + notchScreenInfo.hasNotch);
                    if (!notchScreenInfo.hasNotch) {
                        //如果不是刘海屏，就设置为全屏
                        SoftKeyboardFixerForFullscreen.assistActivity(ForwardDetailsActivity.this);
                        StatusBarCompat.translucentStatusBar(ForwardDetailsActivity.this, true);
                        topBar.adaptVideo();
                        //设置评论View 的顶部占位栏的高度（为了不遮住状态栏）
                        int statusBarHeight = Utils.getStatusBarHeight(ForwardDetailsActivity.this);
                        if (statusBarHeight == 0) {
                            statusBarHeight = Utils.dpToPx(20, ForwardDetailsActivity.this); //如果没获取到 状态栏高度，按20dp 处理
                        }
                        commentView.setPlaceHolderHeight(statusBarHeight);
                    } else {
                        topBar.adaptVideoHasNotch();
                        commentView.setPlaceHolderHeight(0);
                    }
                }
            });
            //bottomBar 在布局文件中设置的高度是45dp ，因为在onCreate（）里面没法获取View的高度
            commentBottomBar.scrollBackground(-Utils.dpToPx(45, this));
            ViewGroup.LayoutParams params = videoPlayer.getLayoutParams();
            params.height = getResources().getDisplayMetrics().heightPixels;//设置videoPlayer 高度为屏幕高度
            LinkedHashMap map = new LinkedHashMap();
            String url = forward.getVideo();
            String remoteUrl;
            if (url != null && url.startsWith("http")) {
                remoteUrl = url;
            } else {
                remoteUrl = AliOssService.TOPIC_VIDEO_PRE_URL + url;
            }
            String proxyUrl = MyApplication.getProxy(this).getProxyUrl(remoteUrl);//视频缓存代理
            map.put("高清", proxyUrl);
            JZDataSource jzDataSource = new JZDataSource(map, "");
            jzDataSource.looping = true;
            // jzDataSource.currentUrlIndex = 2;
            JzvdStd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_CROP);
            videoPlayer.setUp(jzDataSource, JzvdStd.SCREEN_FULLSCREEN);
            videoPlayer.fullscreenButton.setVisibility(View.INVISIBLE);
            videoPlayer.setVisibility(View.VISIBLE);
            videoPlayer.startVideo();
            String coverUrl ;
            if (!TextUtils.isEmpty(forward.getVideoCover())) {
                coverUrl = AliOssService.TOPIC_IMAGE_PRE_URL + forward.getVideoCover();
            } else {
                coverUrl = remoteUrl;
            }
            // videoPlayer.bottomContainer.setVisibility(View.VISIBLE);
            // Glide.with(this).load(remoteUrl).into(videoPlayer.thumbImageView);
            GlideLoadUtils.glideLoad(this, coverUrl, videoPlayer.thumbImageView);
//            if (forward.getPictures() != null && forward.getPictures().size() != 0) {
//                videoPlayer.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                GlideApp.with(this).load(forward.getPictures().remove(0)).into(videoPlayer.thumbImageView);
//            }
        } else {
            commentView.setPlaceHolderHeight(0);
            //如果没有视频的情况下，让sv_container 位于top_bar的下方，不然top_bar会遮住一部分内容
            videoPlayer.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.BELOW, R.id.top_bar);
            refreshLayout.setLayoutParams(params);

        }
        initPicturesList();
        Integer commentSize = forward.getCommentSize();
        if (commentSize == null) {
            commentSize = 0;
        }

        Integer praiseSize = forward.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 0;
        }
        commentBottomBar.init(commentSize, praiseSize, forward.isHadPraise(), manager, this);

        tv_forwardReason.setText(forward.getReason());
        tv_receipt.setText(forward.getReceipt());
        tv_address.setText(forward.getAddress());
        donationView.init(forward, this);
        initRefreshLayout();
    }


    void loadData(String forwardId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .getForwardInfo_v1(forwardId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() && result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            //showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            //  showToast(getString(R.string.system_busy));
                            return;
                        }

                        Object data = result.getData();
                        if (data == null) {
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) data;
                        Log.d(TAG, "onResponse:获取转赠详情完成 " + jsonObject.toString());
                        forward = jsonObject.toJavaObject(Forward.class);
                        init();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        // showToast(getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void initBottomSheetBehavior() {
        bottomSheetBehavior = BottomSheetBehaviorV2.fromV2(findViewById(R.id.comment_view));
        bottomSheetBehavior.setHideable(true);
        //设置默认先隐藏
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View view, int newState) {
                //Log.d(TAG, "onStateChanged: " + newState);
                if ((newState == BottomSheetBehavior.STATE_SETTLING || newState == BottomSheetBehavior.STATE_COLLAPSED) && lastState == BottomSheetBehavior.STATE_EXPANDED) {//如果从完全展示到开始收折，那么隐藏软键盘
                    hideSoftKeyboard();
                    commentBottomBar.showHint("说点什么");
                    commentView.prepareComment();
                }
                if (newState == BottomSheetBehavior.STATE_EXPANDED || newState == BottomSheetBehavior.STATE_COLLAPSED || newState == BottomSheetBehavior.STATE_HIDDEN) {
                    lastState = newState;
                }
            }

            @Override
            public void onSlide(@NonNull View view, float slideOffset) {
                float scrollY = ((1 + slideOffset) * view.getHeight());
                if (!Float.isNaN(scrollY)) {
                    commentBottomBar.setCommentLayoutTranslationY(scrollY);
                }
            }
        });
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                //  refreshData();
            }

            @Override
            public void onLoadingMore() {
                if (donationView.isHasNextPage()) {
                    donationView.loadData();
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }


    private void initPicturesList() {
        //主题有可能是每页图片的
        if (forward.getPictures() == null || forward.getPictures().size() == 0) {
            return;
        }
        pictureAdapter = new PictureAdapter(this, forward.getPictures());
        LinearLayoutManager linearLayoutManager_1 = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        rv_pictureList.setLayoutManager(linearLayoutManager_1);
        rv_pictureList.setAdapter(pictureAdapter);
        //不加这句，滑动不顺畅，加了这句，recyclerView的item 一次全部加载了，
        rv_pictureList.setNestedScrollingEnabled(false);
    }

//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.iv_chat:
//                User u = new User(manager.getuId());
//                u.setUsername(manager.getUsername());
//                u.setAvatar(manager.getAvatar());
//                u.setArea(manager.getArea());
//                u.setGender(getGender(manager));
//                // Boolean bol_isMyFriend = DemoHelper.getInstance().saveContanctInMemory(u);
//                startActivity(new Intent(ForwardDetailsActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, manager.getuId()));
//                break;
//            case R.id.iv_icon:
////                Bundle bundle1 = new Bundle();
////                bundle1.putSerializable("toUser", manager);
////                startActivity(new Intent(TopicDetailsActivity.this, UserProfileActivity.class).putExtras(bundle1));
//                User u1 = new User(manager.getuId());
//                u1.setUsername(manager.getUsername());
//                u1.setAvatar(manager.getAvatar());
//                u1.setArea(manager.getArea());
//                u1.setGender(getGender(manager));
//                //Boolean bol_isMyFriend1 = DemoHelper.getInstance().saveContanctInMemory(u1);
//                startActivity(new Intent(ForwardDetailsActivity.this, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, manager));
//
//                break;
//
//        }
//    }

    @OnClick(R.id.rl_target_user_info)
    public void toUserProfile() {
        startActivity(new Intent(ForwardDetailsActivity.this, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
    }

    @OnClick(R.id.ll_location)
    public void showLocation() {
        startActivity(new Intent(this, LocationMapActivity.class).putExtra(Constant.EXTRA_INFO_FORWARD, forward));
    }

    private void setOnScrollListener() {
        //view.OnScrollChangeListener 用这个接口的话，level必须大于 23
        sv_container.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // Log.d(TAG, "垂直方向滑动距离：" + scrollY);
                ForwardDetailsActivity.this.scrollY = scrollY;
                if (videoPlayer.isShown()) {
                    topBar.scrollTitleBarBackground(scrollY, screenHeight);
                    scrollBottomBarBackground(scrollY);
                    if (videoPlayer.bottomProgressBar.isShown()) {
                        videoPlayer.bottomProgressBar.setVisibility(View.INVISIBLE);
                    }
                }


                if (scrollY < oldScrollY) {
                    // 向下滑动
                    // 下滑复位bottomBar: 视图rl_primary是GONE状态，那么让rl_primary显示出来
                    commentBottomBar.hideCommentEditView();
                    //   Log.d(TAG, "下滑，显示bottomBar");

                    animateAndDisplayBottomBar(300);
                }


                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    //滑动到底部，隐藏bottomBar
                    animateAndHideBottomBar();

                }
            }
        });
    }


    void scrollBottomBarBackground(int scrollY) {
        if (scrollY - commentBottomBar.getHeight() <= 0) {

            commentBottomBar.scrollBackground(scrollY - commentBottomBar.getHeight());
        } else {
            commentBottomBar.scrollBackground(0);

        }
    }


    private void animateAndDisplayBottomBar(long duration) {
        if (!bottomBarIsHide || isShowingDisplayAnimate) {
            return;
        }
        if (viewAnimator == null) {
            viewAnimator = new ViewAnimator();
        }
        if (isShowingHideAnimate) {
            Log.d(TAG, "取消隐藏BottomBar的动画");
            viewAnimator.cancel();
        }
        isShowingDisplayAnimate = true;
        viewAnimator.animate(commentBottomBar).translationY(commentBottomBar.getTranslationY(), 0).duration(duration).onStop(new AnimationListener.Stop() {
            @Override
            public void onStop() {
                isShowingDisplayAnimate = false;
                bottomBarIsHide = false;
            }
        }).start();
    }

    private void animateAndHideBottomBar() {
        if (bottomBarIsHide || isShowingHideAnimate) {
            return;
        }
        if (isShowingDisplayAnimate) {
            Log.d(TAG, "取消显示BottomBar的动画");
            viewAnimator.cancel();
        }
        isShowingHideAnimate = true;
        if (viewAnimator == null) {
            viewAnimator = new ViewAnimator();
        }
        viewAnimator.animate(commentBottomBar).translationY(commentBottomBar.getTranslationY(), commentBottomBar.getHeight()).duration(300).onStop(new AnimationListener.Stop() {
            @Override
            public void onStop() {
                isShowingHideAnimate = false;
                // view.setVisibility(View.GONE);
                bottomBarIsHide = true;
            }
        }).start();


    }


    /**
     * 发表一个评论后，滑动scrollView，显示出自己发表的评论
     */
    void scrollToCommentView() {
//        ViewGroup firstCommentView = (ViewGroup) commentListView.getChildAt(0);
//        int showMoreCommentLayoutHeight = 0;
//        if (firstCommentView.findViewById(R.id.rl_show_more_child_comment) != null) {
//            showMoreCommentLayoutHeight = firstCommentView.findViewById(R.id.rl_show_more_child_comment).getHeight();
//        }
//        Log.d(TAG, "onResponse:showMoreCommentLayoutHeight     " + showMoreCommentLayoutHeight);
//        if (isCover(firstCommentView)) {
//            final int scrollY;
//            if (commentListView.getAdapter().getItemCount() >= 2) {
//                scrollY = commentListView.getTop() - screenHeight + firstCommentView.getHeight() - showMoreCommentLayoutHeight + commentBottomBar.getHeight();//显示一个评论 +bottomBar 的高度
//
//            } else {
//                scrollY = commentListView.getTop() - screenHeight + firstCommentView.getHeight() - showMoreCommentLayoutHeight;//显示一个评论到可见区域
//            }
//            Log.d(TAG, "onResponse: 需要滑动到评论区" + scrollY);
//            Handler handler = new Handler();
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    sv_container.scrollTo(0, scrollY);
//
//                }
//            }, 500);
//
//        }
    }


    void showBottomDialog() {

        List<String> strings = new ArrayList<>();
        String loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
        if (TextUtils.equals(forward.getManagerUser().getuId(), loginUserId) || TextUtils.equals(forward.getTargetUser().getuId(), loginUserId)) {//如果此FORWARD的发布者就是自己或者此forward 的受赠人就是自己，那么可以编辑这个 forward
            strings.add(Constant.BOTTOM_ITEM_NAME_EDIT);
        } else {
            strings.add(Constant.BOTTOM_ITEM_NAME_ACCUSATION);
        }
        BottomDialog bottomDialog = new BottomDialog(this, strings, this);
        bottomDialog.show();

    }


    private String getGender(User targetUser) {
        String gender = null;
        if (targetUser.getGender() != null) {
            if (targetUser.getGender().equals(1)) {
                gender = "女";
            } else if (targetUser.getGender().equals(0)) {
                gender = "男";
            }
        } else {
            gender = "未设置";
        }
        return gender;
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        JzvdStd.goOnPlayOnResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JzvdStd.goOnPlayOnPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        JzvdStd.resetAllVideos();
    }

    @Override
    protected void onStart() {
        super.onStart();


    }

    /**
     * 判断view 是否全部可见
     *
     * @param view
     * @return
     */
    private boolean isCover(View view) {
        boolean cover;
        Rect rect = new Rect();
        cover = view.getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= view.getMeasuredWidth() && rect.height() >= view.getMeasuredHeight()) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void onHideCommentView() {
        hideSoftKeyboard();
        int screenHeight = getWindow().getDecorView().getHeight();
        Log.i(TAG, "hideCommentView: 屏幕高度:" + screenHeight);
        bottomSheetBehavior.setStateHidden(screenHeight);
    }

    @Override
    public void onLoadCommentSuccess(boolean hasNextCommentPage) {
    }

    @Override
    public void onLoadCommentError() {

    }

    @Override
    public void showToast(String message) {
        super.showToast(message);
    }

    @Override
    public void firstLoadDataComplete(int topicPraiseSize, boolean hadPraise) {
        progressBar.setVisibility(View.GONE);
        commentBottomBar.changeLikeImage(hadPraise);
        commentBottomBar.setPraiseSize(topicPraiseSize);
    }

    @Override
    public void onCreateNormalCommentSuccess() {
        commentBottomBar.commitComplete();
    }

    public void firstLoadDataComplete(boolean hadPraise) {
        progressBar.setVisibility(View.GONE);
        commentBottomBar.changeLikeImage(hadPraise);
    }


    public void onCreateCommentSuccess() {
        commentBottomBar.commitComplete();
        //移动到评论区
        // sv_container.scrollTo(0,commentListView.getTop());
        scrollToCommentView();
    }


    @Override
    public void onCreateChildCommentSuccess() {
        commentBottomBar.commitComplete();
    }

    @Override
    public void onCreateCommentError() {
        commentBottomBar.setCommitButton(true);
        super.showToast(getString(R.string.system_busy));
    }

    @Override
    public void showProgressBar(boolean isShowProgressBar) {
        if (isShowProgressBar && !progressBar.isShown()) {
            progressBar.setVisibility(View.VISIBLE);
        } else if (!isShowProgressBar && progressBar.isShown()) {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLoadDonationComplete() {
        refreshLayout.refreshComplete();
    }

    @Override
    public void onHaveNotMoreData() {
        handler.postDelayed(runnable, 2000);
    }


    @Override
    public void onCommitDonationComplete() {
        showToast(donationView, getString(R.string.donation_complete));

    }

    @Override
    public void onCommentItemClick(String hint) {
        commentBottomBar.showHint(hint);
        commentBottomBar.showSoftKeyBord();
        animateAndDisplayBottomBar(300);

    }

    @Override
    public void onCommit(String content) {
        hideSoftKeyboard();
        commentView.commitComment(content);
    }

    @Override
    public void onAddPraise() {
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .addTopicPraise(forward.getfId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();

                    }
                });
    }

    @Override
    public void onRemovePraise() {
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .removeTopicPraise(forward.getfId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    @Override
    public void onPrepareComment() {
        commentView.prepareComment();

        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {

            if (hasVideo) {//如果有视频
                if (scrollY > screenHeight / 2) {//播放器向上滑出屏幕的一半，评论框全部展开
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    bottomSheetBehavior.setSkipCollapsed(true);
                } else {//半展开
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    bottomSheetBehavior.setSkipCollapsed(false);
                }
            } else {//没有视频，全部展开
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                bottomSheetBehavior.setSkipCollapsed(true);

            }
        }

    }

    @Override
    public void onApplyForManager() {

    }

    @Override
    public void onLeftImageClick() {
        finish();
    }

    @Override
    public void onRightImageClick() {
        showBottomDialog();
    }

    @Override
    public void onDialogItemViewClick(int position, String itemName) {
        if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_EDIT)) {
            // TODO: 2018/11/29 进入编辑页面
            showToast("暂未启用");

        } else if (TextUtils.equals(itemName, Constant.BOTTOM_ITEM_NAME_ACCUSATION)) {
            accusationForward();
        }
    }

    void accusationForward() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .accusationForward(forward.getfId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                        }
                        Log.d(TAG, "onResponse: 举报完成");
                        showToast(getString(R.string.accusation_complete));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        progressBar.setVisibility(View.GONE);

                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    @Override
    protected void onAccountChange() {
        super.onAccountChange();
        loadData(forward.getfId());
        commentBottomBar.showHintNotClearContent("说点什么");
        commentView.onAccountChange();
    }
}
